﻿$(document).ready(function() {
    // Load initial data when document is ready
    loadData();

    function editSchool(schoolId) {
        $.get(`http://localhost:5000/schools/${schoolId}`, function(data) {
            $('#schoolId').val(data.schoolId);
            $('#schoolName').val(data.name);
        });
    }

    function editClassroom(classroomId) {
        $.get(`http://localhost:5000/classrooms/${classroomId}`, function(data) {
            $('#classroomId').val(data.classroomId);
            $('#classroomName').val(data.name);
            $('#classroomSchoolId').val(data.schoolId);
        });
    }

    function editStudent(studentId) {
        $.get(`http://localhost:5000/students/${studentId}`, function(data) {
            $('#studentId').val(data.studentId);
            $('#studentName').val(data.name);
            $('#studentAge').val(data.age);
            $('#studentClassroomId').val(data.classroomId);
            $('#studentSchoolId').val(data.schoolId);
        });
    }

    // Function to delete
    function deleteSchool(schoolId) {
        if (confirm('Are you sure you want to delete this school?')) {
            $.ajax({
                url: `http://localhost:5000/schools/${schoolId}`,
                method: 'DELETE',
                success: function() {
                    alert('School deleted!');
                    loadData(); // Reload the data
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting school:', error);
                }
            });
        }
    }

    function deleteClassroom(classroomId) {
        if (confirm('Are you sure you want to delete this classroom?')) {
            $.ajax({
                url: `http://localhost:5000/classrooms/${classroomId}`,
                method: 'DELETE',
                success: function() {
                    alert('Classroom deleted!');
                    loadData(); // Reload the data
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting classroom:', error);
                }
            });
        }
    }

    function deleteStudent(studentId) {
        if (confirm('Are you sure you want to delete this student?')) {
            $.ajax({
                url: `http://localhost:5000/students/${studentId}`,
                method: 'DELETE',
                success: function() {
                    alert('Student deleted!');
                    loadData(); // Reload the data
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting student:', error);
                }
            });
        }
    }

    // Bind edit and delete functions to table buttons dynamically
    $(document).on('click', '.edit-btn', function() {
        const tableId = $(this).closest('table').attr('id');
        const itemId = $(this).data('id');
        if (tableId === 'schoolsTable') {
            editSchool(itemId);
        } else if (tableId === 'classroomsTable') {
            editClassroom(itemId);
        } else if (tableId === 'studentsTable') {
            editStudent(itemId);
        }
    });

    $(document).on('click', '.delete-btn', function() {
        const tableId = $(this).closest('table').attr('id');
        const itemId = $(this).data('id');
        if (tableId === 'schoolsTable') {
            deleteSchool(itemId);
        } else if (tableId === 'classroomsTable') {
            deleteClassroom(itemId);
        } else if (tableId === 'studentsTable') {
            deleteStudent(itemId);
        }
    });

    // Add School
    $('#schoolForm').on('submit', function(e) {
        e.preventDefault();
        const schoolName = $('#schoolName').val();
        const schoolId = $('#schoolId').val();
        const method = schoolId ? 'PUT' : 'POST';
        const url = schoolId ? `http://localhost:5000/schools/${schoolId}` : 'http://localhost:5000/schools';
        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify({ name: schoolName }),
            success: function(result) {
                alert('School saved!');
                loadData(); // Reload the data
                $('#schoolForm')[0].reset(); // Clear the form
            },
            error: function(xhr, status, error) {
                console.error('Error saving school:', error);
            }
        });
    });

    // Add Classroom
    $('#classroomForm').on('submit', function(e) {
        e.preventDefault();
        const classroomName = $('#classroomName').val();
        const schoolId = $('#classroomSchoolId').val();
        const classroomId = $('#classroomId').val();
        const method = classroomId ? 'PUT' : 'POST';
        const url = classroomId ? `http://localhost:5000/classrooms/${classroomId}` : 'http://localhost:5000/classrooms';
        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify({ name: classroomName, schoolId: parseInt(schoolId, 10) }),
            success: function(result) {
                alert('Classroom saved!');
                loadData(); // Reload the data
                $('#classroomForm')[0].reset(); // Clear the form
            },
            error: function(xhr, status, error) {
                console.error('Error saving classroom:', error);
            }
        });
    });

    // Add Student
    $('#studentForm').on('submit', function(e) {
        e.preventDefault();
        const studentName = $('#studentName').val();
        const age = $('#studentAge').val();
        const classroomId = $('#studentClassroomId').val();
        const schoolId = $('#studentSchoolId').val();
        const studentId = $('#studentId').val();
        const method = studentId ? 'PUT' : 'POST';
        const url = studentId ? `http://localhost:5000/students/${studentId}` : 'http://localhost:5000/students';
        $.ajax({
            url: url,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify({ name: studentName, age: parseInt(age, 10), classroomId: parseInt(classroomId, 10), schoolId: parseInt(schoolId, 10) }),
            success: function(result) {
                alert('Student saved!');
                loadData(); // Reload the data
                $('#studentForm')[0].reset(); // Clear the form
            },
            error: function(xhr, status, error) {
                console.error('Error saving student:', error);
            }
        });
    });


    function loadData() {
        // Fetch and display schools
        $.get('http://localhost:5000/schools', function(data) {
            $('#schoolsTable tbody').empty();
            if (data && data.$values) {
                data.$values.forEach(school => {
                    addRowToTable('schoolsTable', school.schoolId, [school.schoolId, school.name]);
                });
            }
        });

        // Fetch and display classrooms
        $.get('http://localhost:5000/classrooms', function(data) {
            $('#classroomsTable tbody').empty();
            if (data && data.$values) {
                data.$values.forEach(classroom => {
                    addRowToTable('classroomsTable', classroom.classroomId, [classroom.classroomId, classroom.name, classroom.schoolId]);
                });
            }
        });

        // Fetch and display students
        $.get('http://localhost:5000/students', function(data) {
            $('#studentsTable tbody').empty();
            if (data && data.$values) {
                data.$values.forEach(student => {
                    addRowToTable('studentsTable', student.studentId, [student.studentId, student.name, student.age, student.classroomId, student.schoolId]);
                });
            }
        });

        // Fetch and display logs
        $.get('http://localhost:5000/logs', function(data) {
            $('#logsTable tbody').empty();
            if (data && data.$values) {
                data.$values.forEach(log => {
                    addRowToTable('logsTable', log.logId, [log.logId, log.timestamp, log.action, log.description]);
                });
            }
        });
    }

    function addRowToTable(tableId, rowId, values) {
        let table = document.getElementById(tableId).getElementsByTagName('tbody')[0];
        let newRow = table.insertRow(table.rows.length);
        newRow.setAttribute('data-id', rowId);

        values.forEach(value => {
            let newCell = newRow.insertCell();
            newCell.textContent = value;
        });

        if (tableId !== "logsTable"){
            let actionCell = newRow.insertCell();
            actionCell.innerHTML = `
            <button class="btn btn-warning edit-btn" data-id="${rowId}">Edit</button>
            <button class="btn btn-danger delete-btn" data-id="${rowId}">Delete</button>
        `;
        }
        
    }
});
